package com.ithuameng.notice.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * netty服务
 */
public class NettyServer {

    /***
     * netty服务端启动
     * @param port : 可指定端口启动
     */
    public void start(int port) {
        System.out.println("准备启动 --> netty...");

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        EventLoopGroup boos = new NioEventLoopGroup();

        EventLoopGroup worker = new NioEventLoopGroup();

        serverBootstrap
                .group(boos, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new HttpServerCodec());

                        channel.pipeline().addLast(new HttpObjectAggregator(65536));

                        channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));

                        // 创建您自己的Websocket处理程序来编写所需的业务逻辑
                        channel.pipeline().addLast(new MyWebSocketHandler());
                    }
                }).bind(port);
    }
}
